package com.moxie.face.liveness.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.moxie.face.Constants;
import com.moxie.face.MainActivity;
import com.moxie.face.R;
import com.moxie.face.liveness.result.data.LivenessResult;
import com.moxie.face.ocr.result.CardResultPresenter;
import com.moxie.face.ocr.result.data.FileType;
import com.moxie.face.ocr.result.data.ResUploadFile;
import com.moxie.liveness.MXLivenessSDK;
import com.moxie.liveness.ui.LivenessActivity;
import com.moxie.liveness.util.LivenessUtils;
import com.moxie.liveness.util.MXProtoBufUtil;
import com.moxie.liveness.util.MXReturnResult;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;

public class MXLivenessDetectResultActivity extends Activity {
    private static final String TAG = "MXLivenesResultActivity";

    public static final String KEY_DETECT_RESULT = "key_detect_result";


    private ImageView mIvResultCenter;
    private RelativeLayout mRlytSmall;
    private ImageView mIvResultSmall;
    private ImageView mIvBack;
    private TextView mTvResultCount;
    private TextView mTvRestartDetect;
    private CardResultPresenter mCardPresenter;
    private MXReturnResult mReturnResult;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_liveness_detect_result_main);

        getIntentData();
        initView();
        initPresenter();
        getSelfVerification();
    }

    private void initPresenter() {
        mCardPresenter = new CardResultPresenter();
    }

    private void getIntentData() {
        Intent intent = getIntent();
        if (intent != null) {
            mReturnResult = (MXReturnResult) intent.getSerializableExtra(KEY_DETECT_RESULT);
        }
    }

    private void initView() {
        mIvResultCenter = (ImageView) findViewById(R.id.id_iv_result_center);
        mRlytSmall = (RelativeLayout) findViewById(R.id.id_rlyt_small);
        mIvResultSmall = (ImageView) findViewById(R.id.id_iv_result_small);
        mTvResultCount = (TextView) findViewById(R.id.id_tv_main_result_count);
        mIvBack = (ImageView) findViewById(R.id.id_iv_back);


        mIvBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onClickBack();
            }
        });

        mRlytSmall.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(mReturnResult != null) {
                    toShowImageResult();
                }
            }
        });

        refreshData();
    }


    private void refreshData() {
        if (mReturnResult != null) {
            MXLivenessSDK.MXLivenessImageResult[] imageResultArr = mReturnResult.getImageResults();
            if (imageResultArr != null) {
                int size = imageResultArr.length;
                mTvResultCount.setText(size + "p");
                if (size > 0) {
                    MXLivenessSDK.MXLivenessImageResult imageResult = imageResultArr[0];
                    Bitmap imageBitmap = BitmapFactory.decodeByteArray(imageResult.image, 0, imageResult.image.length);
                    mIvResultCenter.setImageBitmap(imageBitmap);
                    mIvResultSmall.setVisibility(View.VISIBLE);
                    mIvResultSmall.setImageBitmap(imageBitmap);
                }else {
                    mIvResultSmall.setVisibility(View.GONE);
                }
            }
            // protoBuf文件
            byte[] protoBuf = MXProtoBufUtil.getProtoBuf();
            String saveFilePath = Environment
                    .getExternalStorageDirectory().getAbsolutePath()
                    + File.separator
                    + "liveness" + File.separator;
            LivenessUtils.saveFile(protoBuf, saveFilePath, "proto_buf_file");
        }
    }

    private void onClickBack() {
        finish();
    }

    private void toShowImageResult() {
        Intent intent = new Intent(this, MXLivenessDetectShowActivity.class);
        intent.putExtra(MXLivenessDetectShowActivity.KEY_DETECT_IMAGE_RESULT, mReturnResult);
        startActivity(intent);
    }


    /**
     * 活体检测成功
     */
    private void getSelfVerification() {
        /***********************************************
         * 请将图片上传到自己服务端,调用魔蝎接口进行实人认证  *
         *                                             *
         ***********************************************/

        MXLivenessSDK.MXLivenessImageResult[] images = mReturnResult.getImageResults();

        String filePath = Environment.getExternalStorageDirectory()
                + File.separator + "MXFace" + File.separator ;
        String fileName = System.currentTimeMillis()+".jpg";
        File file = new File(filePath,fileName);
        if (!file.exists()){
            file.getParentFile().mkdirs();
        }

        try {
            OutputStream outputStream = new FileOutputStream(file);
            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream);
            bufferedOutputStream.write(images[0].image);
        } catch (Exception e) {
            e.printStackTrace();
        }
        mCardPresenter.uploadPicture(file, FileType.LIVENESS.getType(), new CardResultPresenter.INetworkCallback() {
            @Override
            public void callback(String result) {
                ResUploadFile resUploadFile = JSON.parseObject(result,ResUploadFile.class);
                String fid = resUploadFile.getData().getFid();
                selfVerification(fid);
            }

            @Override
            public void fail(String error) {

            }
        });

    }

    public void selfVerification(String fid){
        mCardPresenter.getSelfVerification(fid, new CardResultPresenter.INetworkCallback() {
            @Override
            public void callback(String result) {
                LivenessResult livenessResult=JSON.parseObject(result,LivenessResult.class);
                if (livenessResult.getData()!=null && livenessResult.getData().getStatus().equals("1")){
                    showToast("人证比对成功");
                }else {
                    showToast("认证比对失败:"+livenessResult.getData().getReason());
                }
            }

            @Override
            public void fail(String error) {
                showToast("人证比对失败："+error);
            }
        });
    }

    private void showToast(final String message) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(MXLivenessDetectResultActivity.this, message, Toast.LENGTH_SHORT).show();
            }
        });
    }


}
